<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <!-- 用户信息模块 -->
      <div class="user-profile">
        <h2 class="section-title">个人信息</h2>

        <!-- 头像上传 -->
        <div class="avatar-section">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="handleUploadAvatar"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="userInfo.avatar"
              :src="userInfo.avatar"
              class="avatar"
              alt=""
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="avatar-tips">点击修改头像</div>
        </div>

        <!-- 用户信息表单 -->
        <el-form
          ref="userForm"
          :model="userInfo"
          label-width="100px"
          class="user-form"
        >
          <el-form-item label="用户名">
            <el-input
              v-model="userInfo.username"
              placeholder="请输入用户名"
              class="form-input"
            />
          </el-form-item>

          <el-form-item label="手机号">
            <el-input
              v-model="userInfo.mobile"
              placeholder="请输入手机号"
              class="form-input"
            />
          </el-form-item>

          <el-form-item label="电子邮箱">
            <el-input
              v-model="userInfo.email"
              placeholder="请输入电子邮箱"
              class="form-input"
            />
          </el-form-item>

          <el-form-item class="form-actions">
            <el-button
              type="primary"
              @click="handleSaveProfile"
              class="save-btn"
            >
              保存修改
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 地址管理模块 -->
      <div class="address-management">
        <h2 class="section-title">地址管理</h2>
        <el-button type="primary" @click="showAddressModal">添加地址</el-button>
        <div class="address-list">
          <div
            v-for="address in addressList"
            :key="address.id"
            class="address-item"
          >
            <div class="address-header" style="margin-top: 100px">
              <el-tag
                v-if="address.isDefault"
                type="success"
                class="default-tag"
              >
                默认地址
              </el-tag>
              <div class="contact-info">
                <span class="receiver">{{ address.receiverName }}</span>
                <span class="mobile">{{ address.mobile }}</span>
              </div>
            </div>
            <div
              class="address-header"
              style="margin-left: 400px; margin-top: -20px"
            >
              <div class="region-info">
                <span>{{ address.province }}</span>
                <span>{{ address.city }}</span>
                <span>{{ address.district }}</span>
              </div>
              <div class="detail-address">{{ address.detailAddress }}</div>
            </div>
            <div class="address-actions">
              <el-button type="text" @click="handleEditAddress(address)">
                编辑
              </el-button>
              <el-button
                type="text"
                @click="handleDeleteAddress(address.addressId)"
              >
                删除
              </el-button>
              <el-button
                type="text"
                @click="
                  address.isDefault
                    ? unsetDefaultAddress(address.addressId)
                    : setDefaultAddress(address.addressId)
                "
              >
                {{ address.isDefault ? "取消默认地址" : "设为默认地址" }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 地址弹窗 -->
    <el-dialog
      title="地址信息"
      v-model="addressModalVisible"
      width="40%"
      :before-close="handleCloseAddressModal"
    >
      <el-form
        ref="addressForm"
        :model="currentAddress"
        label-width="100px"
        class="address-form"
      >
        <el-form-item label="收货人">
          <el-input
            v-model="currentAddress.receiverName"
            placeholder="请输入收货人姓名"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="手机号">
          <el-input
            v-model="currentAddress.mobile"
            placeholder="请输入手机号"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="省">
          <el-input
            v-model="currentAddress.province"
            placeholder="请输入省份"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="市">
          <el-input
            v-model="currentAddress.city"
            placeholder="请输入城市"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="区">
          <el-input
            v-model="currentAddress.district"
            placeholder="请输入区县"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input
            v-model="currentAddress.detailAddress"
            placeholder="请输入详细地址"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="默认地址">
          <el-checkbox v-model="currentAddress.isDefault"
            >设为默认地址
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseAddressModal">取 消</el-button>
          <el-button type="primary" @click="handleSaveAddress">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 地址弹窗 -->
    <el-dialog
      title="地址信息"
      v-model="addressModalVisible2"
      width="40%"
      :before-close="handleCloseAddressModal2"
    >
      <el-form
        ref="addressForm"
        :model="currentAddress"
        label-width="100px"
        class="address-form"
      >
        <el-form-item label="收货人">
          <el-input
            v-model="currentAddress.receiverName"
            placeholder="请输入收货人姓名"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="手机号">
          <el-input
            v-model="currentAddress.mobile"
            placeholder="请输入手机号"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="省">
          <el-input
            v-model="currentAddress.province"
            placeholder="请输入省份"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="市">
          <el-input
            v-model="currentAddress.city"
            placeholder="请输入城市"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="区">
          <el-input
            v-model="currentAddress.district"
            placeholder="请输入区县"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input
            v-model="currentAddress.detailAddress"
            placeholder="请输入详细地址"
            class="form-input"
          />
        </el-form-item>

        <el-form-item label="默认地址">
          <el-checkbox v-model="currentAddress.isDefault"
            >设为默认地址
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseAddressModal2">取 消</el-button>
          <el-button type="primary" @click="handleSaveAddress2"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  FileControllerService,
  UserAddressAddRequest,
  UserAddressControllerService,
  UserControllerService,
  UserUpdateRequest,
} from "@/generated";
import TypeConverter from "@/utils/TypeConverter";
import { ElLoading, UploadRequestOptions } from "element-plus";
import router from "@/router";

interface UserInfo {
  userId: string;
  username: string;
  mobile: string;
  email: string;
  avatar?: string;
  role: number;
}

interface Address {
  id?: string;
  receiverName: string;
  mobile: string;
  province: string;
  city: string;
  district: string;
  detailAddress: string;
  isDefault: boolean;
}

// 用户信息
const userInfo = reactive<UserInfo>({
  userId: "",
  username: "",
  mobile: "",
  email: "",
  role: 0,
});

const uploadUserInfo = reactive<UserUpdateRequest>({
  userId: "",
  mobile: "",
  email: "",
  avatar: "",
});

// 地址相关
const addressList = ref<Address[]>([]);
const addressModalVisible = ref(false);
const addressModalVisible2 = ref(false);
const currentAddress = reactive<UserAddressAddRequest>({
  addressId: 0,
  receiverName: "",
  mobile: "",
  province: "",
  city: "",
  district: "",
  detailAddress: "",
  isDefault: 0,
});

/**
 * 头像上传处理
 */
// 优化后的头像上传处理
const handleUploadAvatar = async (options: UploadRequestOptions) => {
  const loading = ElLoading.service({
    lock: true,
    text: "头像上传中...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    // 1. 获取有效用户ID
    const userId = Number(userInfo.userId);
    if (isNaN(userId)) {
      Message.error("用户身份信息异常，请重新登录");
      return router.push("/login");
    }

    // 2. 文件验证
    const allowedTypes = ["image/jpeg", "image/png"];
    if (!allowedTypes.includes(options.file.type)) {
      Message.error("仅支持 JPG/PNG 格式");
      return;
    }

    if (options.file.size > 2 * 1024 * 1024) {
      Message.error("图片大小不能超过2MB");
      return;
    }

    // 3. 创建FormData包装文件
    const formData = new FormData();
    formData.append("file", options.file); // 关键修改：使用FormData
    formData.append("userId", userId.toString()); // 附加用户ID

    // 4. 执行上传（修改后的上传方式）
    const uploadRes = await FileControllerService.uploadFile(formData);

    if (uploadRes.code !== 0 || !uploadRes.data) {
      Message.error(uploadRes.message || "头像上传失败");
      return;
    }

    // 5. 构建更新参数
    const updateParams: UserUpdateRequest = {
      userId: userId,
      avatar: uploadRes.data,
    };
    console.log("更新参数", updateParams);
    // 6. 更新用户信息
    const updateRes = await UserControllerService.updateUser(updateParams);
    if (updateRes.code === 0) {
      Message.success("头像更新成功");
      await loadData();
    } else {
      Message.error(updateRes.message || "更新失败");
    }
  } catch (error: any) {
    console.error("上传过程中出错:", error);
    Message.error(
      error.response?.data?.message || error.message || "系统繁忙，请稍后重试"
    );
  } finally {
    loading.close();
  }
};

// 文件上传前校验（可选，增强体验）
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    Message.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    Message.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 加载数据
const loadData = async () => {
  try {
    // 加载用户信息
    const userRes = await UserControllerService.getCurrentUser();
    Object.assign(userInfo, userRes.data);

    // 加载地址列表
    const addressRes = await UserAddressControllerService.getUserAddressList();
    addressList.value = addressRes.data;
  } catch (error) {
    Message.error("数据加载失败");
  }
};

// 保存个人信息
const handleSaveProfile = async () => {
  try {
    const res = await UserControllerService.updateUser(uploadUserInfo);
    if (res.code === 0) {
      Message.success("个人信息更新成功");
      await loadData();
    }
  } catch (error) {
    Message.error("更新失败");
  }
};

// 地址操作
const showAddressModal = async () => {
  resetAddressForm();
  const res = await UserAddressControllerService.createUserAddress({
    receiverName: currentAddress.receiverName,
    mobile: currentAddress.mobile,
    province: currentAddress.province,
    city: currentAddress.city,
    district: currentAddress.district,
    detailAddress: currentAddress.detailAddress,
    isDefault: currentAddress.isDefault,
  });
  console.log(res);
  if (res.code === 0) {
    Message.success("地址保存成功");
  } else {
    Message.error("地址保存失败");
  }
  addressModalVisible.value = true;
};

const resetAddressForm = () => {
  Object.assign(currentAddress, {
    id: undefined,
    receiverName: "",
    mobile: "",
    province: "",
    city: "",
    district: "",
    detailAddress: "",
    isDefault: false,
  });
};

const handleEditAddress = (address: Address) => {
  Object.assign(currentAddress, address);
  addressModalVisible2.value = true;
};

const handleSaveAddress = async () => {
  try {
    // 添加地址
    const res = await UserAddressControllerService.createUserAddress(
      currentAddress
    );
    if (res.code === 0) {
      Message.success("地址保存成功");
      await loadData();
    }
    addressModalVisible.value = false;
  } catch (error) {
    Message.error("操作失败");
  }
};

const handleSaveAddress2 = async () => {
  console.log("跟新地址");
  try {
    // 更新地址
    const res = await UserAddressControllerService.updateUserAddress({
      addressId: currentAddress.addressId,
      receiverName: currentAddress.receiverName,
      mobile: currentAddress.mobile,
      province: currentAddress.province,
      city: currentAddress.city,
      district: currentAddress.district,
      detailAddress: currentAddress.detailAddress,
    });
    console.log(res);
    if (res.code === 0) {
      Message.success("地址更新成功");
      await loadData();
      addressModalVisible2.value = false;
    }
  } catch (error) {
    Message.error("操作失败");
  }
};

const handleDeleteAddress = async (id: string) => {
  try {
    const number = TypeConverter.toNumber(id);
    const res = await UserAddressControllerService.deleteUserAddress({
      addressId: number,
    });
    if (res.code === 0) {
      await loadData();
      Message.success("地址删除成功");
    }
  } catch (error) {
    Message.error("删除失败");
  }
};

// 设置默认地址
const setDefaultAddress = async (id: string) => {
  try {
    const number = TypeConverter.toNumber(id);
    const res = await UserAddressControllerService.updateUserAddressStatus({
      addressId: number,
      isDefault: 1,
    });
    if (res.code === 0) {
      await loadData();
      Message.success("默认地址设置成功");
    }
  } catch (error) {
    Message.error("设置失败");
  }
};

// 取消默认地址
const unsetDefaultAddress = async (id: string) => {
  console.log("id", id);
  try {
    const number = TypeConverter.toNumber(id);
    const res = await UserAddressControllerService.updateUserAddressStatus({
      addressId: number,
      isDefault: 0,
    });
    console.log(res);
    if (res.code === 0) {
      await loadData();
      Message.success("默认地址取消成功");
    }
  } catch (error) {
    Message.error("取消失败");
  }
};

// 辅助方法
const fullAddress = (address: Address) => {
  return `${address.province} ${address.city} ${address.district} ${address.detailAddress}`;
};

// 关闭地址弹窗
const handleCloseAddressModal = () => {
  addressModalVisible.value = false;
};

const handleCloseAddressModal2 = () => {
  addressModalVisible2.value = false;
};
// 初始化加载
onMounted(loadData);
</script>

<style lang="scss" scoped>
.profile-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;

  .profile-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  }

  .section-title {
    color: #303133;
    font-size: 20px;
    margin-bottom: 25px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
  }

  // 头像区域
  .avatar-section {
    text-align: center;
    margin-bottom: 30px;

    .avatar-uploader {
      display: inline-block;
      border: 2px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 120px;
      height: 120px;
      transition: border-color 0.3s;

      &:hover {
        border-color: #409eff;
      }

      .avatar {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 50%;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
      }
    }

    .avatar-tips {
      color: #909399;
      font-size: 12px;
      margin-top: 10px;
    }
  }

  // 用户信息表单
  .user-form {
    max-width: 600px;
    margin: 0 auto;
    padding: 0 20px;

    .form-input {
      width: 100%;
    }

    .form-actions {
      text-align: center;
    }

    .save-btn {
      width: 200px;
      margin-top: 20px;
      margin-left: 100px;
    }
  }

  // 地址管理
  .address-management {
    margin-top: 40px;

    .address-item {
      margin-bottom: 16px;
      padding: 16px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      }

      .address-header {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        .default-tag {
          margin-right: 10px;
        }

        .contact-info {
          display: flex;
          gap: 20px;
          font-size: 14px;

          .receiver {
            font-weight: 500;
            color: #303133;
          }

          .mobile {
            color: #606266;
          }
        }
      }

      .address-content {
        .region-info {
          display: flex;
          gap: 10px;
          margin-bottom: 8px;
          color: #606266;
          font-size: 13px;

          span:not(:last-child)::after {
            content: "/";
            margin-left: 10px;
            color: #c0c4cc;
          }
        }

        .detail-address {
          color: #606266;
          font-size: 13px;
          line-height: 1.5;
        }
      }

      .address-actions {
        display: flex;
        justify-content: flex-end;
        gap: 8px;
        border-bottom: 1px solid #ebeef5;

        .el-button {
          padding: 7px 12px;
        }
      }
    }
  }
}

// 弹窗样式调整
.el-dialog {
  .el-form-item {
    margin-bottom: 18px;

    &__label {
      font-weight: 500;
    }
  }

  .el-checkbox {
    margin-left: 80px;
  }

  .dialog-footer {
    padding: 20px 0 0;
    text-align: right;
  }
}
</style>
